namespace SubSonic
{
    using System;
    using System.Data.Common;

    internal class AutomaticConnectionScope : IDisposable
    {
        private readonly DbConnection _dbConnection;
        private bool _disposed;
        private readonly bool _isUsingSharedConnection;

        internal AutomaticConnectionScope(DataProvider provider)
        {
            if (provider == null)
            {
                throw new ArgumentNullException("provider");
            }
            if (provider.CurrentSharedConnection != null)
            {
                this._dbConnection = provider.CurrentSharedConnection;
                this._isUsingSharedConnection = true;
            }
            else
            {
                this._dbConnection = provider.CreateConnection();
            }
        }

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        public void Dispose(bool disposing)
        {
            if (!this._disposed && disposing)
            {
                if (!this._isUsingSharedConnection)
                {
                    this._dbConnection.Dispose();
                }
                this._disposed = true;
            }
        }

        public T GetConnection<T>() where T: DbConnection
        {
            return (T) this.Connection;
        }

        internal DbConnection Connection
        {
            get
            {
                return this._dbConnection;
            }
        }

        internal bool IsUsingSharedConnection
        {
            get
            {
                return this._isUsingSharedConnection;
            }
        }
    }
}

